<?php

namespace common\models\person;

use Yii;

/**
 * This is the model class for table "{{%addon_article_tag_map}}".
 *
 * @property int $tag_id 标签id
 * @property int $article_id 文章id
 */
class PersonHobbyMap extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%person_hobby_map}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['hobby_id', 'person_id'], 'integer'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'hobby_id' => '爱好ID',
            'person_id' => '个人信息ID',
        ];
    }

    /**
     * @param $person_id
     */
    public static function getHobbysByPersonId($person_id)
    {
        return self::findAll(['person_id' => $person_id]);
    }

    /**
     * @param $article_id
     * @param $tags
     * @return bool
     * @throws \yii\db\Exception
     */
    static public function addHobbys($person_id, $hobby)
    {
        // 删除原有标签关联
        self::deleteAll(['person_id' => $person_id]);
        if ($person_id && !empty($hobby)) {
            $data = [];
            foreach ($hobby as $v) {
                $data[] = [$v, $person_id];
            }
            $field = ['hobby_id', 'person_id'];
            // 批量插入数据
            Yii::$app->db->createCommand()->batchInsert(self::tableName(), $field, $data)->execute();

            return true;
        }

        return false;
    }
}
